#include "main.h"

struct shm_addr *shm_buf;

void *msgque_get(void *date)
{
	int i;

	key_t key;
	int msgid;
	msg_buf = (msg_t *)malloc(sizeof(msg_t));

	if((key = ftok("/app", 'g')) < 0){
		perror("ftok");
		exit(1);
	}

	if((msgid = msgget(key, IPC_CREAT|0666)) < 0){
		perror("msgget");
		exit(1);
	}

	while(1){
		msgrcv(msgid, msg_buf, sizeof(*msg_buf) - sizeof(long), 1L, 0);
		pthread_mutex_unlock(&mutex3);
	}
}

void *zig_write(void *date)
{
	int ret = 0;

	while(1){
		pthread_mutex_lock(&mutex3);
		if(msg_buf->text[0] == 0x31){ //阈值信息
			pthread_mutex_unlock(&mutex4);
		}else{               //命令解析
			ret = write(fd, &msg_buf->text[0], sizeof(unsigned char));
			if(ret < 0){
				perror("usb_write");
			}
		}
	}
}

void *thld_info(void *date)
{
	int i, j;
	int *p = NULL;

	shm_buf = (struct shm_addr *)malloc(sizeof(struct shm_addr));

	shm_buf->rt_status.storage_no[1].temperatureMIN = 5.0;
	shm_buf->rt_status.storage_no[1].temperatureMAX = 50.0;
	shm_buf->rt_status.storage_no[1].humidityMIN = 10.0;
	shm_buf->rt_status.storage_no[1].humidityMAX = 50.0;
	shm_buf->rt_status.storage_no[1].illuminationMIN = 10.0;
	shm_buf->rt_status.storage_no[1].illuminationMAX = 500.0;

	while(1){
		pthread_mutex_lock(&mutex4);
		for(i = 1; i < 32; i+= 4){
			if(msg_buf->text[i] != 0){
				p = (int *)&msg_buf->text[i];
				while(1){
					if((0x1 << j++) & (*p) != 0){
						(*p) >>= (j - 1);
					}
				}
			}
			switch(i){
			case 1:
				shm_buf->rt_status.storage_no[1].temperatureMAX = (float)*p;
				break;
			case 5:
				shm_buf->rt_status.storage_no[1].temperatureMIN = (float)*p;
				break;
			case 9:
				shm_buf->rt_status.storage_no[1].humidityMAX = (float)*p;
				break;
			case 13:
				shm_buf->rt_status.storage_no[1].humidityMIN = (float)*p;
				break;
			case 17:
				shm_buf->rt_status.storage_no[1].illuminationMAX = (float)*p;
				break;
			case 21:
				shm_buf->rt_status.storage_no[1].illuminationMIN = (float)*p;
				break;
			}
		}
	}
}
